#include "../include/task_queue.h"

//初始化任务队列
int init_TaskQueue(ptaskQueue_t pQueue)
{
    pQueue->size = 0;
    pQueue->pFront = pQueue->pRear = NULL;
    pthread_cond_init(&pQueue->cond, NULL);
    pthread_mutex_init(&pQueue->mutex, NULL);
    pQueue->exit_flag = 0;
    return 0;
}

//入队
int en_TaskQueue(ptaskQueue_t pQueue, ptaskNode_t pNew)
{
    if (pQueue->pFront == NULL) {
        pQueue->pFront = pQueue->pRear = pNew;
    }
    else {
        pQueue->pRear->pNext = pNew;
        pQueue->pRear = pNew;
    }

    ++pQueue->size;
    return 0;
}

//得到队头元素，同时出队
int de_TaskQueue(ptaskQueue_t pQueue, ptaskNode_t *pOut)
{
    //没有元素
    if (pQueue->size == 0) {
        return -1;
    }
    //有元素，取出，更新队头
    *pOut = pQueue->pFront;
    pQueue->pFront = pQueue->pFront->pNext;

    //只有一个元素，更新队尾
    if (pQueue->size == 1) {
        pQueue->pRear = NULL;
    }
    
    //减小队列长度
    --pQueue->size;
    return 0;
}


